import requests

from geektime_0.service.litemall.api.api_base import ApiBase
from geektime_0.service.litemall.model.cart import Cart
from geektime_0.service.litemall.model.goods import Goods
from geektime_0.service.litemall.config.base_data import url


class CartHttpApi(ApiBase):

    # 查看购物车
    def index(self):
        r = requests.get(
            f'{url}/wx/cart/index',
            headers = {'X-Litemall-Token': self.session.get_token()}
        )
        if r.status_code == 200:
            cart = Cart()
            cart.cartList = []
            for item in r.json()['data']['cartList']:
                goods = Goods()
                goods.id = item['goodsId']
                goods.name = item['goodsName']
                goods.retailPrice = item['price']
                goods.number = item['number']
                goods.productId = item['productId']
                cart.cartList.append(goods)
            cart.checkedGoodsAmount = r.json()['data']['cartTotal']['checkedGoodsAmount']
            cart.checkedGoodsCount = r.json()['data']['cartTotal']['checkedGoodsCount']
            cart.goodsAmount = r.json()['data']['cartTotal']['goodsAmount']
            cart.goodsCount = r.json()['data']['cartTotal']['goodsCount']
            return cart
        else:
            return None

    def update(self):
        pass

    # 删除购物车中的商品
    def delete(self, productIds):
        r = requests.post(
            f'{url}/wx/cart/delete',
            json = {'productIds': productIds},
            headers = {'X-Litemall-Token': self.session.get_token()}
        )
        return r

    # 清空购物车
    def clear(self):
        cart = self.index()
        if cart.cartList:
            productIds = []
            for item in cart.cartList:
                productIds.append(item.productId)
            self.delete(productIds)
